<template>
  <div class="migration-left flex-column">
    <el-collapse v-model="activeNames" class="h-100 overflow-auto">
      <el-collapse-item :title="$t('MIGRATION_LINK_RANGE') + '：'" name="1">
        <el-form ref="form" label-width="auto" class="pt-10">
          <el-form-item :label="$t('SERVICE_NAME')">
            <el-select v-model="bizId" filterable clearable :placeholder="$t('SERVICE_NAME')">
              <el-option
                v-for="item in bizList"
                :key="item.bizId"
                :value="item.bizId"
                :label="item.bizName"
              />
            </el-select>
          </el-form-item>
          <el-divider />
          <!-- A区域选择 -->
          <el-form-item :label="$t('A_END_STATION_NAME')">
            <el-input v-model="formData.aStationId" class="hide" />
            <el-select
              v-if="bizId"
              v-model="formData.aStationId"
              filterable
              clearable
              :placeholder="$t('A_END_STATION_NAME')"
            >
              <el-option
                v-for="item in bizStationList"
                :key="item.regionId"
                :value="item.regionId"
                :label="item.regionName"
              />
            </el-select>
            <region-cascader
              v-else
              class="w-100"
              :placeholder="'A_END_STATION_NAME'"
              @change="aStationChange"
            />
          </el-form-item>
          <!-- a端节点 -->
          <el-form-item :label="$t('ANODE')">
            <el-select
              v-model="formData.aNodeId"
              :placeholder="$t('SELECT_ANODE')"
              clearable
              filterable
            >
              <el-option
                v-for="item in aNodeList"
                :key="item.nodeId"
                :value="item.nodeId"
                :label="item.nodeName"
              />
            </el-select>
          </el-form-item>
          <!-- a端节点端口 -->
          <el-form-item :label="$t('A_END_NODE_PORT')">
            <el-select
              v-model="formData.aPortId"
              :placeholder="$t('SELECT_PORT')"
              clearable
              filterable
            >
              <el-option
                v-for="item in aPortList"
                :key="item.portId"
                :value="item.portId"
                :label="item.bizName"
              />
            </el-select>
          </el-form-item>
          <!-- Z区域选择 -->
          <el-form-item :label="$t('Z_END_STATION_NAME')" class="mt-30">
            <el-select
              v-model="formData.zStationId"
              filterable
              clearable
              :disabled="!formData.aPortId && !bizId"
              :placeholder="$t('Z_END_STATION_NAME')"
            >
              <el-option
                v-for="item in bizStationList"
                :key="item.regionId"
                :value="item.regionId"
                :label="item.regionName"
              />
            </el-select>
          </el-form-item>
          <!-- z端节点 -->
          <el-form-item :label="$t('ZNODE')">
            <el-select
              v-model="formData.zNodeId"
              :placeholder="$t('SELECT_ZNODE')"
              :disabled="!formData.zStationId"
              clearable
              filterable
            >
              <el-option
                v-for="item in zNodeList"
                :key="item.nodeId"
                :value="item.nodeId"
                :label="item.nodeName"
              />
            </el-select>
          </el-form-item>
          <!-- z端节点端口 -->
          <el-form-item :label="$t('Z_END_NODE_PORT')">
            <el-select
              v-model="formData.zPortId"
              :disabled="!formData.zNodeId"
              clearable
              filterable
              :placeholder="$t('SELECT_PORT')"
            >
              <el-option
                v-for="item in zPortList"
                :key="item.portId"
                :value="item.portId"
                :label="item.bizName"
              />
            </el-select>
          </el-form-item>
          <el-divider />
        </el-form>
        <div class="flex justify-end">
          <el-button :disabled="!formData.zStationId" @click="$debounce(getRouteList)">{{
            $t('SEARCH_ROUTE')
          }}</el-button>
          <el-button :disabled="!formData.zPortId" @click="showLinkView">{{
            $t('VIEW_LINK_DETAILS')
          }}</el-button>
        </div>
      </el-collapse-item>
      <el-collapse-item :title="$t('MIGRATION_POINT_LIST') + '：'" name="2">
        <el-table ref="tableBox" height="100%" border :data="tableList">
          <template slot="empty">
            <NullData />
          </template>
          <el-table-column type="index" :label="$t('SEQUENCE')" :width="resetSize(60)" />
          <el-table-column :label="$t('DEVICE') + 1">
            <el-table-column
              :label="$t('STATION') + '/' + $t('DEVICE')"
              show-overflow-tooltip
              prop="startNode.nodeName"
            >
              <template v-slot="scope">
                {{ getStationName(scope.row.startNode) }}
              </template>
            </el-table-column>
            <el-table-column
              :label="$t('PORT_NAME')"
              show-overflow-tooltip
              prop="startPort.portName"
            >
              <template v-slot="scope">
                {{ $utils.handleServiceI18n(scope.row.startPort.portName) }}
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column :label="$t('LINK_TO_DEVICE') + 2">
            <el-table-column
              :label="$t('STATION') + '/' + $t('DEVICE')"
              show-overflow-tooltip
              prop="endNode.nodeName"
            >
              <template v-slot="scope">
                {{ getStationName(scope.row.endNode) }}
              </template>
            </el-table-column>
            <el-table-column
              :label="$t('PORT_NAME')"
              show-overflow-tooltip
              prop="endPort.portName"
            >
              <template v-slot="scope">
                {{ $utils.handleServiceI18n(scope.row.endPort.portName) }}
              </template>
            </el-table-column>
          </el-table-column>
        </el-table>
        <div class="flex justify-end pt-10">
          <el-button @click="$emit('cancel')">{{ $t('CANCEL') }}</el-button>
          <el-button @click="$emit('connect')">{{ $t('CONNECT') }}</el-button>
        </div>
      </el-collapse-item>
    </el-collapse>
  </div>
</template>
<script>
  import { mapGetters } from 'vuex'
  import bizOpenApi from '@/api/oen/BizOpenApi'
  import linkMigration from '@/api/oen/LinkMigrationApi'
  import bizChannelApi from '@/api/oen/BizChannelApi'
  import nodeApi from '@/api/oen/NodeApi'
  import { handleServiceI18n } from '@/service/i18n'
  import RegionCascader from '@/components/RegionCascader'
  import { deepClone } from '@/utils/common'

  export default {
    components: {
      RegionCascader
    },
    props: {
      tableList: {
        type: Array,
        default: () => []
      }
    },
    data() {
      return {
        activeNames: ['1', '2'],
        bizId: '',
        formData: {
          aStationId: null,
          aNodeId: '',
          aPortId: '',
          zStationId: null,
          zNodeId: '',
          zPortId: '',
          aNodeData: {},
          zNodeData: {},
          aPortData: {},
          zPortData: {}
        },
        aNodeList: [],
        zNodeList: [],
        aPortList: [],
        zPortList: [],
        bizStationList: [],
        bizList: [],
        bizNodeList: [],
        bizPortList: [],
        oldFromData: null
      }
    },
    computed: {
      ...mapGetters(['baseRegionList'])
    },
    watch: {
      bizId(newVal) {
        this.bizStationList = []
        this.bizNodeList = []
        this.bizPortList = []
        this.formData = this.$options.data().formData
        newVal && this.getBizDetail(newVal)
      },
      'formData.aStationId': function(newVal) {
        if (this.bizId) {
          this.formData.aNodeId = ''
          this.formData.aPortId = ''
          this.aNodeList = []
        } else {
          this.formData = this.$options.data().formData
        }
        this.formData.aStationId = newVal
        if (!newVal) return
        if (this.bizId) {
          this.aNodeList = this.bizNodeList.filter(i => i.stationId === newVal)
        } else {
          this.getNodeList(newVal, 'a')
        }
      },
      'formData.aNodeId': function(newVal) {
        this.aPortList = []
        this.formData.aPortData = {}
        this.formData.aPortId = ''
        if (!this.bizId) {
          this.formData.zStationId = ''
        }
        if (!newVal) return
        const nodeData = this.aNodeList.find(i => i.nodeId === newVal)
        this.formData.aNodeData = nodeData
        if (this.bizId) {
          this.aPortList = this.bizPortList.filter(i => i.deviceId === newVal)
        } else {
          this.getPortList(nodeData, 'a')
        }
      },
      // 根据az端口类型判断是否显示double，single类型默认收发
      'formData.aPortId': function(newVal) {
        if (!this.bizId) {
          this.formData.zStationId = ''
        }
        this.getPortPresentChannel(newVal)
      },
      'formData.zStationId': function(newVal) {
        this.zNodeList = []
        this.formData.zNodeId = ''
        this.formData.zPortId = ''
        if (!newVal) return
        this.zNodeList = this.bizNodeList.filter(i => i.stationId === newVal)
      },
      'formData.zNodeId': function(newVal) {
        this.zPortList = []
        this.formData.zPortId = ''
        if (!newVal) return
        this.zPortList = this.bizPortList.filter(i => i.deviceId === newVal)
        const nodeData = this.zNodeList.find(i => i.nodeId === newVal)
        this.formData.zNodeData = nodeData
      }
    },
    created() {
      this.getBizList()
    },
    methods: {
      getBizList() {
        bizOpenApi.list().then(res => {
          this.bizList = res || []
        })
      },
      getBizDetail(bizId) {
        bizChannelApi.getDetailByBizId({ bizId: bizId }).then(res => {
          this.formateList(res)
          this.mainData = res
        })
      },
      formateList(data) {
        let stationList = []
        const nodeList = []
        const portList = []
        data.forEach(i => {
          i.segmentList.forEach(j => {
            stationList.push(j.startNode.stationId)
            stationList.push(j.endNode.stationId)
            if (!nodeList.some(z => z.nodeId === j.startNode.nodeId)) {
              nodeList.push(j.startNode)
            }
            if (!nodeList.some(z => z.nodeId === j.endNode.nodeId)) {
              nodeList.push(j.endNode)
            }
            j.startPort.bizName = handleServiceI18n(j.startPort.bizName)
            j.endPort.bizName = handleServiceI18n(j.endPort.bizName)
            portList.push(j.startPort)
            portList.push(j.endPort)
          })
        })
        stationList = Array.from(new Set(stationList))
        stationList = stationList
          .map(i => this.baseRegionList.find(j => j.regionId === i) || null)
          .filter(i => !!i)
        this.bizStationList = stationList
        this.bizNodeList = nodeList
        this.bizPortList = portList
        // console.log('portList', portList)
      },
      getRouteList() {
        this.$emit('getRouteList', {
          startStationId: this.formData.aStationId,
          endStationId: this.formData.zStationId
        })
        this.oldFromData = deepClone(this.formData)
      },
      getPortPresentChannel(data) {
        if (!data || this.bizId) return
        linkMigration.portPresentChannel({ portId: data }).then(res => {
          if (
            res[0].startNodeId !== this.formData.aNodeId &&
            res[0].endNodeId !== this.formData.aNodeId
          ) {
            res.reverse()
          }
          res.forEach((i, index) => {
            if (
              (index === 0 && i.startNodeId !== this.formData.aNodeId) ||
              (index !== 0 && i.startNodeId !== res[index - 1].endNodeId)
            ) {
              const item = {
                startNodeId: i.endNodeId,
                startPortId: i.endPortId,
                startPortCategory: i.endPortCategory,
                startNode: i.endNode,
                startPort: i.endPort,
                endNodeId: i.startNodeId,
                endPortId: i.startPortId,
                endPortCategory: i.startPortCategory,
                endPort: i.startPort,
                endNode: i.startNode
              }
              i = { ...i, ...item }
            }
          })
          const mainData = [{ segmentList: res }]
          this.formateList(mainData)
          this.mainData = mainData
        })
      },
      // 获取端口列表
      getPortList(data, side) {
        // 通过接口获取节点列表(节点名称等信息)
        nodeApi
          .portList({
            nodeId: data.nodeId,
            status: null
          })
          .then(res => {
            // 光分器只能选择输入
            res = data.nodeCategory === 'LIGHT_SPLIT' ? [res[0]] : res
            res.forEach(i => {
              i.bizName = handleServiceI18n(i.bizName)
            })
            this[side + 'PortList'] = res
          })
      },
      // a站点改变
      aStationChange(data) {
        this.formData.aStationId = data
      },
      // 获取站点下节点
      getNodeList(stationId, side) {
        nodeApi.queryList({ stationIdList: [stationId] }).then(res => {
          this[side + 'NodeList'] = res || []
        })
      },
      showLinkView() {
        if (!this.formData.aNodeId) {
          this.$message.error(
            this.$t('SELECT_NAME', {
              msg: this.$t('ANODE')
            })
          )
          return
        }
        if (!this.formData.aPortId && !this.bizId) {
          this.$message.error(
            this.$t('SELECT_NAME', {
              msg: this.$t('A_END_NODE_PORT')
            })
          )
          return
        }
        if (!this.formData.zNodeId) {
          this.$message.error(
            this.$t('SELECT_NAME', {
              msg: this.$t('ZNODE')
            })
          )
          return
        }
        if (!this.formData.zPortId && !this.bizId) {
          this.$message.error(
            this.$t('SELECT_NAME', {
              msg: this.$t('Z_END_NODE_PORT')
            })
          )
          return
        }

        if (
          this.oldFromData.aStationId !== this.formData.aStationId ||
          this.oldFromData.zStationId !== this.formData.zStationId
        ) {
          this.$confirm(this.$t('CONFIRM_CONTINUE_MIGRATION'), { type: 'warning' })
            .then(() => {
              this.goCut()
            })
            .catch(() => {})
        } else {
          this.goCut()
        }
      },
      goCut() {
        let mainData = deepClone(this.mainData)
        if (
          this.bizId &&
          this.bizNodeList.findIndex(i => i.nodeId === this.formData.aNodeId) >
          this.bizNodeList.findIndex(i => i.nodeId === this.formData.zNodeId)
        ) {
          mainData = mainData.map(i => {
            i.segmentList.reverse()
            i.segmentList = i.segmentList.map(j => {
              const item = {
                startNodeId: j.endNodeId,
                startPortId: j.endPortId,
                startPortCategory: j.endPortCategory,
                startNode: j.endNode,
                startPort: j.endPort,
                endNodeId: j.startNodeId,
                endPortId: j.startPortId,
                endPortCategory: j.startPortCategory,
                endPort: j.startPort,
                endNode: j.startNode
              }
              return { ...j, ...item }
            })
            return i
          })
        }
        this.$emit('goCutover', {
          formData: this.formData,
          mainData: mainData
        })
      },
      getStationName(nodeData) {
        if (!nodeData) return ''
        const stationData = this.baseRegionList.find(
          i => i.regionId === nodeData.stationId
        )
        return (stationData ? stationData.regionName + '/' : '') + nodeData.nodeName
      },
      getSaveData() {
        let bizData = null
        if (this.bizId) {
          bizData = this.bizList.find(i => i.bizId === this.bizId)
        }
        this.formData.aPortData = this.aPortList.find(i => i.portId === this.formData.aPortId)
        this.formData.zPortData = this.zPortList.find(i => i.portId === this.formData.zPortId)
        return {
          bizData: bizData,
          formData: this.formData
        }
      }
    }
  }
</script>
<style lang="scss">
  @import '@/assets/css/mixin.module.scss';
  .migration-left {
    width: 30%;
    min-width: 410px;
    padding: 10px;
    @include themeify {
      border: 1px solid themed('tableBorderColor');
    }
    .el-form-item {
      padding-right: 20px;
    }
    .el-form .el-divider {
      margin: 0 0 10px 0;
    }
  }
</style>
